package com.liang.security.authentication;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: liangjy
 * @Date:2022/2/5 21:59
 * @Package_name: com.liang.security.authentication
 * @Description:
 * 自定义鉴定失败处理器
 *  * 鉴定失败后不跳转登录页面
 *  * 而直接将错误提示的JSON返回
 */
@Component
public class AuthenticationFailedHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        System.err.println("登录失败~~~~~~~");
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        response.setCharacterEncoding("UTF-8");
        JSON.writeJSONString(response.getWriter(),e.getMessage());
    }
}
